package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.dataConfig.ResponseStatus;
import com.dongdongshop.dataConfig.dataResult;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.shiro.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("seller")
public class SellerController {
    private Logger logger = LoggerFactory.getLogger(SellerController.class);
    @Reference
    private SellerService sellerService;

    @RequestMapping("toHome")
    public String toHome(){
        return "admin/home";
    }

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("toAudit")
    public String toAudit(){
        return "admin/audit";
    }

    @RequestMapping("register")
    @ResponseBody
    public dataResult register(TbSeller s){
        try {
            String pwd = s.getPassword();
            String password = ShiroUtils.encryptPassword("MD5",pwd,"admin",3);
            s.setPassword(password);
            Integer i = sellerService.addinfo(s);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName());
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "shoplogin";
    }

    @RequestMapping("login")
    public String login(TbSeller t, Model model){
        /*
         * 使用shiro编写认证操作
         * */
        //1,获取subject
        Subject subject = SecurityUtils.getSubject();
        //2,封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(t.getSellerId(),t.getPassword());
        //3,执行登录方法
        try{
            subject.login(token);
        }catch (UnknownAccountException e){
            model.addAttribute("message","用户名不存在");
            return "shoplogin";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不正确");
            return "shoplogin";
        }
        System.out.println(model.getAttribute("message"));
        return "admin/index";
    }
}
